import { PLAYER_TYPE, WEAPON_TYPE } from "./Core/AppDef";
import { EVT_CREATE_BULLET } from "./Core/AppEvent";
import { dispatchEvent, addListener } from "./Managers/EventManager";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Player extends cc.Component {
    @property(cc.Animation)
    anim: cc.Animation = null;
    @property(cc.Node)
    weapon: cc.Node = null;
    @property(cc.Node)
    hpNode: cc.Node = null;

    playerType : PLAYER_TYPE = PLAYER_TYPE.My;
    weaponType : WEAPON_TYPE = WEAPON_TYPE.My;
    p = cc.v3(0,0,0);
    weaponP = cc.v3(0,0,0);
    weaponAngle = 0;
    attackCooling = 0;
    attackCoolingTime = 0.2;
    nick = "a";
    hp = 100;

    onLoad () {
        this.schedule(()=>{
            this.onMove();
        }, 0.01)
    }

    init (playerType: PLAYER_TYPE, weaponType: WEAPON_TYPE, nick:string) {
        if(playerType){
            this.playerType = playerType;
        }
        if(weaponType){
            this.weaponType = weaponType;
        }
        if(nick){
            this.nick = nick;
        }
        this.hp = 100;
        this.p = cc.v3(0,0,0);
        this.weaponP = cc.v3(0,0,0);
        this.weaponAngle = 0;
    }

    setHpReduce(hit){
        this.hpNode.scaleX = (this.hp - hit) / 100;
        this.hp -= hit;
    }

    getPlayerHp(){
        return this.hp;
    }

    start(){
        this.changeAnim("idle");
    }

    setP(p) {
        this.p = p.multiplyScalar(5);
    }
    
    setWeaponP(data) {
        this.weaponP = data.p.multiplyScalar(5);
        if(data.angle){
            this.weaponAngle = data.angle;
            this.weapon.angle = this.weaponAngle;
        }
        if(data.scalex){
            this.node.scaleX = data.scalex;
        }
    }
    
    onMove () {
        this.node.position = this.node.position.add(this.p);
        if(this.p.mag() !== 0){
            this.changeAnim("run");
        }else{
            this.changeAnim("idle");
        }

        if(this.attackCooling > 0){
            this.attackCooling -= 0.01;
        }

        if(this.weaponP.mag() !== 0 && this.attackCooling <= 0){
            this.weapon.getComponent(cc.Animation).play("weaponAttack");
            this.attackCooling = this.attackCoolingTime;
            let pos = this.weapon.convertToWorldSpaceAR(new cc.Vec3(0,0));
            dispatchEvent(EVT_CREATE_BULLET, {weaponType :this.weaponType, pos:pos, weaponP:this.weaponP,from:this.nick})
        }
    }

    changeAnim(name){
        if(this.anim.currentClip === null || this.anim.currentClip.name !== name){
            this.anim.play(name);
        }
    }

    
}
